import os
import graphml2lua

def to_lua_source(indir, outdir):
    def export_file(indir, outdir, name):
        infile = os.path.abspath(os.path.join(indir, name))
        outfile = os.path.abspath(os.path.join(outdir, name + ".lua"))
        print("lua %s ..." % infile)
        graphml2lua.dump(indir, graphml2lua.load(infile), outfile)

    def export_reference(indir, outdir, name):
        infile = os.path.abspath(os.path.join(indir, name))
        with open(infile, 'r', encoding='utf8') as fp:
            lines = [line.strip() for line in fp.readlines()]
        if len(lines) > 0 and lines[0].startswith('file://'):
            infile = os.path.abspath(os.path.join(indir, lines[0][7:]))
            tree = graphml2lua.load(infile)
        for name in lines[1:]:
            if not name: continue
            outfile = os.path.abspath(os.path.join(outdir,
                os.path.splitext(os.path.basename(name))[0] + ".graphml.lua"))
            print("lua %s %s ..." % (infile, name))
            graphml2lua.dump(indir, tree, outfile, name)

    if not os.path.exists(indir):
        return False

    if not os.path.exists(outdir):
        os.mkdir(outdir)

    for name in os.listdir(indir):
        if os.path.isdir(os.path.join(indir, name)):
            to_lua_source(os.path.join(indir, name), os.path.join(outdir, name))
        elif os.path.isfile(os.path.join(indir, name)):
            if name.endswith('.graphml'):
                export_file(indir, outdir, name)
            elif name.endswith('.reference'):
                export_reference(indir, outdir, name)
    return True
